package cn.afactory.tygz.ui.base.fragments;

import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ListView;

import com.harwkin.nb.popmenu.PopupButton;
import com.harwkin.nb.popmenu.adapter.PopupAdapter;

import java.util.ArrayList;
import java.util.List;

import cn.afactory.tygz.R;
import cn.afactory.tygz.model.Address;
import cn.afactory.tygz.model.AddressItem;
import cn.afactory.tygz.model.City;
import cn.afactory.tygz.model.CityEntity;
import cn.afactory.tygz.model.NearByUserInfo;
import cn.afactory.tygz.model.NearByUserInfoList;
import cn.afactory.tygz.model.Province;
import cn.afactory.tygz.ui.base.adapter.AddressAdapter;
import cn.afactory.tygz.ui.base.utils.NaviUtils;
import cn.afactory.tygz.ui.base.BaseFragment;
import cn.afactory.tygz.ui.base.adapter.NearByPeoplesAdapter;
import cn.afactory.tygz.ui.base.thirdpart.pulltorefresh.PullToRefreshBase;
import cn.afactory.tygz.ui.base.thirdpart.pulltorefresh.PullToRefreshGridView;
import cn.afactory.tygz.ui.base.utils.LocalUtils;
import cn.afactory.tygz.ui.base.utils.ScreenUtil;
import cn.afactory.tygz.ui.base.views.NearByPeopleFilterBar;
import cn.afactory.tygz.ui.sns.controller.SnsControler;

/**
 * 附近的人
 */
public class NearByPeoplesFragment extends BaseFragment{

    private static final String TAG = NearByPeoplesFragment.class.getSimpleName();

    private final int NUM_COLUM = 3;
    private NearByPeoplesAdapter mGridAdapter;
    private List<NearByUserInfo> mList = new ArrayList<NearByUserInfo>();

    private int mImageWidth, mImageHeight;
    private NearByPeopleFilterBar.FilterType mFilterType = NearByPeopleFilterBar.FilterType.NONE;
    private SnsControler mController;

    private PopupButton mGenderFilter, mAgeFilter, mCityFilter;
    private int mFilterSex = -1, mFilterStartAge = -1, mFilterEndAge = -1, mFilterCityCode = -1;

    private ListView provinceListView, cityListView;
    private Address mAddress;
    private CityEntity mCityEntity;
    private List<AddressItem> provinceData = new ArrayList<AddressItem>();
    private List<AddressItem> cityData = new ArrayList<AddressItem>();
    private AddressAdapter provinceAdapter;
    private AddressAdapter cityAdapter;

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what){
            case SnsControler.MSG_NEAR_BY_PEOPLES_OK:
                hideErrorPage(-1);
                NearByUserInfoList userInfoList = (NearByUserInfoList) msg.obj;
                if (null != userInfoList && null != userInfoList.value && userInfoList.value.size() >=0) {
                    if (msg.arg1 == SnsControler.MSG_DATA_FROM_CACHE && mGridAdapter.getCount() == 0 && mLastReqTime == 0) {
                        mList.addAll(userInfoList.value);
                    } else {
                        if (mLastReqTime == 0) {
                            mList.clear();
                        }
                    }
                    mList.addAll(userInfoList.value);
                    mGridAdapter.setmPeopleInfoList(mList);

                    if (plgridView.isRefreshing()) {
                        plgridView.onRefreshComplete();
                    }

                    if (userInfoList.value.size() < mPageSize) {
                        plgridView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                    } else {
                        plgridView.setMode(PullToRefreshBase.Mode.BOTH);
                    }
                } else {
                    if (mGridAdapter.getCount() == 0) {
                        showNullPage(true);
                    }
                }
                break;
            case SnsControler.MSG_NEAR_BY_PEOPLES_KO:
                if (mGridAdapter.getCount() == 0) {
                    hideErrorPage(-1);
                    showErrorPage(msg.arg1, new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            startLoadDatas();
                        }
                    });
                } else {
                    LocalUtils.showToast(mContext, "获取附近的人失败！"/*StringUtil.handlerErrorCode(mContext, msg.arg1)*/);
                }
                break;
            default:
                break;
        }

        // 结束下拉刷新
        if (plgridView.isRefreshing()) {
            plgridView.onRefreshComplete();
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addTitleBar = false;
        mController = new SnsControler(mContext,mUIHandler,"NearByPeoples");
    }

    @Override
    public View onCreateViewCustom(LayoutInflater inflater, ViewGroup container) {
        View view = inflater.inflate(R.layout.fg_near_by_peoples, null);
        initViews(view);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initData();
    }

    private void initViews(View v){
        mGenderFilter = (PopupButton)v.findViewById(R.id.people_gender_filter);
        mAgeFilter = (PopupButton)v.findViewById(R.id.people_age_filter);
        mCityFilter = (PopupButton)v.findViewById(R.id.people_city_filter);
        plgridView = (PullToRefreshGridView)v.findViewById(R.id.lv_people_list);
        plgridView.getRefreshableView().setNumColumns(NUM_COLUM);
        plgridView.getRefreshableView().setHorizontalSpacing(20);
        plgridView.getRefreshableView().setVerticalSpacing(20);

        mGridAdapter = new NearByPeoplesAdapter(mContext, mList, mImageWidth, mImageHeight);
        plgridView.setAdapter(mGridAdapter);
        plgridView.getRefreshableView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                NearByUserInfo userInfo = (NearByUserInfo) mGridAdapter.getItem(position);
                NaviUtils.gotoUserProfileActivity(getActivity(), userInfo.userId, userInfo.nickName);
            }
        });

        mImageWidth = (ScreenUtil.getScreenWidth(getContext()) - getContext().getResources().getDimensionPixelOffset(R.dimen.healthcircle_padding15) * 2
                - getContext().getResources().getDimensionPixelOffset(R.dimen.healthcircle_padding2) * 2) / 3;
        mImageHeight = mImageWidth + getContext().getResources().getDimensionPixelOffset(R.dimen.healthcircle_padding2);

        plgridView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<GridView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
                startLoadDatas();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {
                startLoadSubjectData(false);
            }
        });
    }

    private void initData() {
        startLoadDatas();

        initGenderData();
        initAgeData();
        initCityData();
    }

    private void initGenderData(){
        LayoutInflater inflater = LayoutInflater.from(getActivity());
        View typeView = inflater.inflate(R.layout.sub_second_goods_class, null);
        ListView typeLv = (ListView) typeView.findViewById(R.id.lv);
        final String[] genderType = {"不限", "女士","男士", "其他"};

        //类型
        final PopupAdapter typeAdapter = new PopupAdapter(getActivity(),R.layout.popup_item,genderType,R.drawable.pb_list_item_normal,R.drawable.pb_list_item_press);
        typeLv.setAdapter(typeAdapter);
        typeLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                typeAdapter.setPressPostion(position);
                typeAdapter.notifyDataSetChanged();
                if (position == 0 ) {
                    mGenderFilter.setText("性别");
                } else {
                    mGenderFilter.setText(genderType[position]);
                }
                mGenderFilter.hidePopup();
                if (position == 0) {
                    mFilterSex = -1;
                } else if (position == 1) {
                    mFilterSex = 1;
                } else if (position == 2) {
                    mFilterSex = 0;
                } else {
                    mFilterSex = 2;
                }
                reloadFilterDatas(genderType[position]);
            }
        });
        mGenderFilter.setPopupView(typeView);
    }

    private void initAgeData(){
        LayoutInflater inflater = LayoutInflater.from(getActivity());
        View typeView = inflater.inflate(R.layout.sub_second_goods_class, null);
        ListView typeLv = (ListView) typeView.findViewById(R.id.lv);
        final String[] ageType = {"不限","16岁－20岁","21岁－25岁","26岁-30岁","31岁-40岁", "40岁以上",};

        final PopupAdapter typeAdapter = new PopupAdapter(getActivity(),R.layout.popup_item,ageType,R.drawable.pb_list_item_normal,R.drawable.pb_list_item_press);
        typeLv.setAdapter(typeAdapter);
        typeLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                typeAdapter.setPressPostion(position);
                typeAdapter.notifyDataSetChanged();
                if (position == 0) {
                    mAgeFilter.setText("年龄");
                } else {
                    mAgeFilter.setText(ageType[position]);
                }
                mAgeFilter.hidePopup();
                if (position == 0) {
                    mFilterStartAge = -1;
                    mFilterEndAge = -1;
                } else if (position == 1) {
                    mFilterStartAge = 16;
                    mFilterEndAge = 20;
                } else if (position == 2) {
                    mFilterStartAge = 21;
                    mFilterEndAge = 25;
                } else if (position == 3) {
                    mFilterStartAge = 26;
                    mFilterEndAge = 30;
                } else if (position == 4) {
                    mFilterStartAge = 31;
                    mFilterEndAge = 40;
                } else {
                    mFilterStartAge = 41;
                    mFilterEndAge = -1;
                }
                reloadFilterDatas(ageType[position]);
            }
        });
        mAgeFilter.setPopupView(typeView);
    }

    private void initCityData(){
        LayoutInflater inflater = LayoutInflater.from(getActivity());
        View typeView = inflater.inflate(R.layout.sub_city_class, null);
        provinceListView = (ListView)typeView.findViewById(R.id.lv_left);
        cityListView = (ListView)typeView.findViewById(R.id.lv_right);

        mCityEntity = new CityEntity(mContext);
        provinceAdapter = new AddressAdapter(provinceData, mContext);
        cityAdapter = new AddressAdapter(cityData, mContext);
        initProvinceData();

        provinceListView.setAdapter(provinceAdapter);
        provinceListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    mCityFilter.setText("城市");
                    mFilterCityCode = -1;
                    mCityFilter.hidePopup();
                    reloadFilterDatas("");
                } else {
                    chageDataOnProvince(position);
                }
            }
        });
        cityListView.setAdapter(cityAdapter);
        cityListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                AddressItem addressItem = (AddressItem)cityData.get(position);
                mCityFilter.setText(addressItem.name);
                mFilterCityCode = Integer.valueOf(addressItem.code);
                mCityFilter.hidePopup();
                reloadFilterDatas("");
            }
        });

        mCityFilter.setPopupView(typeView);
    }

    /**
     * 初始化 所有省份
     */
    private void initProvinceData() {
        if (null == mCityEntity) {
            mCityEntity = new CityEntity(mContext);
        }

        if (null != mCityEntity.mProvinceList) {
            if (provinceData.size() > 0) {
                provinceData.clear();
            }
            provinceData.add(new AddressItem("-1","不限", ""));

            for (Province province : mCityEntity.mProvinceList) {
                if (null != province) {
                    AddressItem addressItem = new AddressItem(
                            province.provinceCode, province.provinceName, "");
                    provinceData.add(addressItem);
                }
            }
            provinceAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 点击省份项时 数据改变操作
     *
     * @param arg2
     */
    private void chageDataOnProvince(int arg2) {
        if(null == mAddress){
            mAddress = new Address();
        }
        if (mAddress.city != null) {
            mAddress.city = null;
            mAddress.cityCode = null;
        }
        mAddress.provinceCode = provinceData.get(arg2).code;
        mAddress.province = provinceData.get(arg2).name;
        setCityData(provinceData.get(arg2).code);
    }

    /**
     * 通过省份Code 查询所有城市 绑定Data
     *
     * @param provinceCode
     *            省份Code
     */
    public void setCityData(String provinceCode) {
        if (TextUtils.isEmpty(provinceCode)) {
            return;
        }

        if (null == mCityEntity) {
            mCityEntity = new CityEntity(mContext);
        }

        for (int i = 0; i < mCityEntity.mProvinceList.size(); i++) {
            if (mCityEntity.mProvinceList.get(i).provinceCode
                    .equals(provinceCode)) {
                if (null == cityData) {
                    cityData = new ArrayList<AddressItem>();
                }
                if (cityData.size() > 0) {
                    cityData.clear();
                }
                if (null == mCityEntity.mProvinceList.get(i).mallCityList
                        || mCityEntity.mProvinceList.get(i).mallCityList.size() == 0) {
                    // TODO
                    return;
                }
                for (City city : mCityEntity.mProvinceList.get(i).mallCityList) {
                    if (null != city) {
                        AddressItem addressItem = new AddressItem(
                                city.cityCode, city.cityName, provinceCode);
                        cityData.add(addressItem);
                    }
                }
                cityAdapter.notifyDataSetChanged();
                cityListView.setSelection(0);
            }
        }
    }

    private void reloadFilterDatas(String orderType){
        startLoadDatas();
    }

    private void startLoadDatas(){
        startLoadSubjectData(true);
    }

    /**
     * 加载listview数据
     */
    private int mPageIndex = 0;
    private int mPageSize = 10;
    private long mLastReqTime = System.currentTimeMillis();
    protected void startLoadSubjectData(boolean cleanData) {
        if (cleanData) {
            mPageIndex = 0;
            mLastReqTime = 0;
        }
        mController.loadNearByPeoplesData(mFilterSex,mFilterStartAge,mFilterEndAge,mFilterCityCode,mPageIndex,mPageSize);
    }
}
